"use client"

import {useEffect, useState} from "react"
import {Card, CardContent} from "@/components/ui/card"

interface ComponentPreviewProps {
    code: string
}

export function ComponentPreview({code}: ComponentPreviewProps) {
    const [previewHtml, setPreviewHtml] = useState<string>("")

    useEffect(() => {
        // 从Vue组件代码中提取模板部分
        const extractTemplate = (code: string) => {
            const templateMatch = code.match(/<template>([\s\S]*?)<\/template>/)
            if (templateMatch && templateMatch[1]) {
                return templateMatch[1].trim()
            }
            return "<div>无法提取模板</div>"
        }

        // 简单处理Vue模板语法，转换为静态HTML进行预览
        const processTemplate = (template: string) => {
            // 替换v-for (非常简化的处理)
            let processed = template.replace(/v-for="(\w+) in (\w+)"/g, "data-v-for")

            // 替换v-if, v-else-if, v-else (简化处理)
            processed = processed.replace(/v-if="[^"]*"/g, "")
            processed = processed.replace(/v-else-if="[^"]*"/g, "")
            processed = processed.replace(/v-else/g, "")

            // 替换v-show (简化处理)
            processed = processed.replace(/v-show="[^"]*"/g, "")

            // 替换v-model (简化处理)
            processed = processed.replace(/v-model="[^"]*"/g, "")

            // 替换@click等事件 (简化处理)
            processed = processed.replace(/@\w+="[^"]*"/g, "")

            // 替换:class, :style等绑定 (简化处理)
            processed = processed.replace(/:(class|style)="{[^}]*}"/g, "")

            // 替换{{ }}表达式为示例文本
            processed = processed.replace(/{{([^}]*)}}/g, (match, p1) => {
                const content = p1.trim()
                if (content.includes("item.") || content.includes("user.")) {
                    return "示例数据"
                }
                if (content.includes("count")) {
                    return "0"
                }
                if (content.includes("title") || content.includes("props.title")) {
                    return "标题"
                }
                return "示例文本"
            })

            return processed
        }

        const template = extractTemplate(code)
        const processedHtml = processTemplate(template)
        setPreviewHtml(processedHtml)
    }, [code])

    return (
        <Card>
            <CardContent className="p-6">
                <div className="preview-container" dangerouslySetInnerHTML={{__html: previewHtml}}/>
            </CardContent>
        </Card>
    )
}
